﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;

namespace TripleGameDAL
{
    public class TripleGameDALL
    {
        public static void CreateUser(User u)
        {
            TripleGameEntities dbContext = new TripleGameEntities();
            using (dbContext)
            {
                dbContext.Users.AddObject(u);
                dbContext.SaveChanges();
            }
        }

        public static User GetUserByID(int? id)
        {
            TripleGameEntities dbContext = new TripleGameEntities();
            using (dbContext)
            {
                User u = (from us in dbContext.Users
                          where us.ID == id
                          select us).Single();
                return u;
            }
        }

        public static void CreateGame(Game g)
        {
            TripleGameEntities dbContext = new TripleGameEntities();
            using (dbContext)
            {
                dbContext.Games.AddObject(g);
                dbContext.SaveChanges();
            }
        }

        public static Game GetGameByID(int id)
        {
            TripleGameEntities dbContext = new TripleGameEntities();
            using (dbContext)
            {
                Game g = (from gm in dbContext.Games
                          where gm.ID == id
                          select gm).Single();
                return g;
            }
        }

        public static IEnumerable<Game> GetAllGames()
        {
            TripleGameEntities dbContext = new TripleGameEntities();
            using (dbContext)
            {
                var g = (from gm in dbContext.Games
                         select gm);
                return g.ToList<Game>();
            }
        }

        public static void EditGame(Game g)
        {
            TripleGameEntities dbContext = new TripleGameEntities();
            using (dbContext)
            {
                try
                {
                    dbContext.Games.Attach(g);
                    dbContext.ObjectStateManager.GetObjectStateEntry(g).SetModified();
                    dbContext.Refresh(RefreshMode.ClientWins, g);
                    dbContext.SaveChanges();
                }
                catch (InvalidOperationException)
                {
                    Console.WriteLine("The game was not found. Check if the id is correct");
                }
            }
        }
    }
}
